<script lang="ts" setup name="SocialLoginForm">
import LoginFormTitle from './LoginFormTitle.vue'
import { useIcon } from '@/hooks/web/useIcon'
import { setTenantIdCache, getLoginFormCache, setLoginFormCache, removeLoginFormCache, setToken } from '@/utils/auth'
import { AuthApi } from '@/api/auth'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import router from '@/router'

const { t } = useI18n()
const route = useRoute()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { getLoginState } = useLoginState()
const { push } = useRouter()
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}

const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

// 获取验证码
const getCode = async () => {
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}

// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await AuthApi.Tenant.getIdByName(loginData.loginForm.tenantName) // '租户ID'
    setTenantIdCache(res)
  }
}

// 记住我
const getLoginForm = () => {
  const loginForm = getLoginFormCache()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}

// tricky: 配合LoginForm.vue中redirectUri需要对参数进行encode，需要在回调后进行decode
const getUrlValue = (key: string): string => {
  const url = new URL(decodeURIComponent(location.href))
  return url.searchParams.get(key) ?? ''
}

// 尝试登录: 当账号已经绑定，socialLogin会直接获得token
const tryLogin = async () => {
  try {
    const type = getUrlValue('type')
    const redirect = getUrlValue('redirect')
    const code = route?.query?.code as string
    const state = route?.query?.state as string

    const res = await AuthApi.Social.signIn(type, code, state)
    setToken(res)

    router.push({ path: redirect || '/' })
  } catch (err) {}
}

// 登录
const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    let redirect = getUrlValue('redirect')
    const type = getUrlValue('type')
    const code = route?.query?.code as string
    const state = route?.query?.state as string
    const res = await AuthApi.signIn({
      // 账号密码登录
      username: loginData.loginForm.username,
      password: loginData.loginForm.password,
      captchaVerification: params.captchaVerification,
      // 社交登录
      socialCode: code,
      socialState: state,
      socialType: type
    }) // { code: 200 }
    if (!res) {
      return
    }
    if (loginData.loginForm.rememberMe) {
      setLoginFormCache(loginData.loginForm)
    } else {
      removeLoginFormCache()
    }
    setToken(res)
    if (!redirect) {
      redirect = '/'
    }
    // 判断是否为SSO登录
    if (redirect.toLowerCase().indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect })
    }
  } finally {
    loginLoading.value = false
  }
}

onMounted(() => {
  getLoginForm()
  tryLogin()
})
</script>

<template>
  <el-form v-show="getShow" ref="formLogin" :model="loginData.loginForm" :rules="LoginRules" class="login-form" label-position="top" label-width="120px" size="large">
    <el-row>
      <el-col :span="24">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
          <el-input v-model="loginData.loginForm.tenantName" :placeholder="t('sign.fields.tenant', 'placeholder')" :prefix-icon="iconHouse" link type="primary" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="username">
          <el-input v-model="loginData.loginForm.username" :placeholder="t('sign.fields.username', 'placeholder')" :prefix-icon="iconAvatar" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="password">
          <el-input v-model="loginData.loginForm.password" :placeholder="t('sign.fields.password', 'placeholder')" :prefix-icon="iconLock" show-password type="password" @keyup.enter="getCode()" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <el-row justify="space-between" class="items-center m-6px leading-[0]" style="width: 100%">
            <el-col :span="6">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                {{ t('sign', 'remember') }}
              </el-checkbox>
            </el-col>
            <el-col :offset="6" :span="12">
              <el-link style="float: right" type="primary">{{ t('sign.fields.password', 'forget') }}</el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <CButton :loading="loginLoading" :title="t('sign.in', 'action')" class="w-[100%]" type="primary" @click="getCode()" />
        </el-form-item>
      </el-col>
      <Verify ref="verify" :captchaType="captchaType" :imgSize="{ width: '400px', height: '200px' }" mode="pop" @success="handleLogin" />
    </el-row>
  </el-form>
</template>

<style lang="scss" scoped>
.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
